package com.mqz.seckill.controller;

import com.mqz.seckill.pojo.User;
import com.mqz.seckill.service.GoodsService;
import com.mqz.seckill.service.UserService;
import com.mqz.seckill.vo.GoodsVO;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/goods")
public class GoodsController {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private ThymeleafViewResolver resolver;
    @Resource
    private UserService userService;
    @Resource
    private GoodsService goodsService;

//    @RequestMapping("/toList")
//    public String toList(@CookieValue("userTicket") String userTicket, Model model, HttpServletRequest request, HttpServletResponse response) {
//
//        //        从session中读取登录票据
////        if ((session.getAttribute(userTicket)) == null) {
////            return "login";
////        }
////        User user = (User) session.getAttribute(userTicket);
//
//        User user = userService.getUserByCookie(userTicket, request, response);
//
//        model.addAttribute("user", user);
//        return "goodsList";
//    }

    //使用WebMvc
    @RequestMapping(value = "/toList", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toList(Model model, User user, HttpServletRequest request, HttpServletResponse response) {
        if (user == null) {
            return "login";
        }


        ValueOperations ops = redisTemplate.opsForValue();
        String html = (String) ops.get("goodsList");
        if (StringUtils.hasText(html)) {
            return html;
        }

        model.addAttribute("user", user);
        model.addAttribute("goodsList", goodsService.GoodsVOList());

        WebContext webContext = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
        html = resolver.getTemplateEngine().process("goodsList", webContext);

        //设置页面缓存，60s失效
        if (StringUtils.hasText(html)) {
            ops.set("goodsList", html, 60, TimeUnit.SECONDS);
        }

        return html;
    }

    @RequestMapping(value = "/toDetail/{goodsId}", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toDetail(Model model, User user, @PathVariable Long goodsId, HttpServletRequest request, HttpServletResponse response) {
        if (user == null) {
            return "login";
        }

        ValueOperations ops = redisTemplate.opsForValue();
        String html = (String) ops.get("goodsDetail:" + goodsId);
        if (StringUtils.hasText(html)) {
            return html;
        }


        model.addAttribute("user", user);

        GoodsVO goodsVO = goodsService.getGoodsVOByGoodsId(goodsId);
        model.addAttribute("goods", goodsVO);

        //定义秒杀信息
        Date start = goodsVO.getStartDate();
        Date end = goodsVO.getEndDate();
        Date now = new Date();

        //0-未开始，1-进行中，2-已结束
        int status;
        //距离秒杀开始时间，0-进行中，-1-已结束，单位s
        int remain;

        if (now.before(start)) {
            status = 0;
            remain = (int) ((start.getTime() - now.getTime()) / 1000);
        } else if (now.after(start) && now.before(end)) {
            status = 1;
            remain = 0;
        } else {
            status = 2;
            remain = -1;
        }

        model.addAttribute("secKillStatus", status);
        model.addAttribute("remainSeconds", remain);

        WebContext webContext = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
        html = resolver.getTemplateEngine().process("goodsDetail", webContext);

        //设置页面缓存，60s失效
        if (StringUtils.hasText(html)) {
            ops.set("goodsDetail:" + goodsId, html, 60, TimeUnit.SECONDS);
        }

        return html;
    }
}
